import { ref } from 'vue'
import { useUserStore } from '@/store'
import { showModal, totast } from '@/composables/until'
import { useRouter } from 'vue-router'
import { logOut, updatepassword } from '@/api/manager'
export function useRepassword() {
  const userStore = useUserStore()
  const router = useRouter()
  const fromDrawerRef = ref(null)
  // 修改密码的表单
  const form = ref({
    oldpassword: '',
    password: '',
    repassword: '',
  })
  const rules = {
    oldpassword: [
      { required: true, message: '旧密码不能为空', trigger: 'blur' },
    ],
    password: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
    repassword: [{ required: true, message: '请确认密码', trigger: 'blur' }],
  }
  const ruleFormRef = ref(null)
  // 修改密码抽屉
  const showDrawer = ref(false)
  const loading = ref(false)
  const onSubmit = () => {
    ruleFormRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      console.log(form.value)
      loading.value = true
      updatepassword(form.value)
        .then((res) => {
          console.log(res)

          totast('修改密码成功,请重新登录')
          userStore.logOut()
          // 跳转首页
          router.push('/login')
          // 关闭抽屉
          showDrawer.value = false
          // 重置表单
          ruleFormRef.value.resetFields()
        })
        .finally(() => {
          loading.value = false
        })
    })
  }
  const openRePasswordForm = () => fromDrawerRef.value.open()
  return {
    fromDrawerRef,
    form,
    rules,
    onSubmit,
    ruleFormRef,
    openRePasswordForm,
  }
}

export function useLogout() {
  const userStore = useUserStore()
  const router = useRouter()
  // 退出登录
  function handelLogOut() {
    showModal('您确定要吗？').then((res) => {
      console.log('退出登录')
      logOut().finally(() => {
        userStore.logOut()
        // 退出登录成功
        totast('退出登录成功')
        // 跳转首页
        router.push('/login')
      })
    })
  }
  return { handelLogOut }
}
